package coreutil

import (
	"context"
	"core/config"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/gridfs"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

var (
	MongoUtil *mongo.Database
	client    *mongo.Client
	db        *mongo.Database
)

func InitMongo() (err error) {

	var opt = options.Client().ApplyURI(config.Config.Mongo.URI).
		SetConnectTimeout(5 * time.Second)

	var MaxPoolSize uint64 = 1000
	opt.MaxPoolSize = &MaxPoolSize
	//var pm = &event.PoolMonitor{
	//	func(poolEvent *event.PoolEvent) {
	//		fmt.Println(poolEvent)
	//
	//	},
	//}
	//opt.PoolMonitor = pm

	// 1.连接mongodb
	client, err = mongo.Connect(context.Background(),
		opt)
	if err != nil {
		fmt.Println(err)
		return err
	}

	if err = client.Ping(context.Background(), nil); err != nil {
		fmt.Println(err)
		return err
	}

	// 由于都是对同一个集合进行操作，所以在初始化mongodb时就选择了集合，防止后续出现大量重复代码
	db = client.Database(config.Config.Mongo.Db)
	MongoUtil = db
	fmt.Println("*************MongoDB**************")
	return
}

func GetGridfsBucket(collName string) *gridfs.Bucket {
	var bucket *gridfs.Bucket
	// 使用默认文件集合名称
	if collName == "" || collName == options.DefaultName {
		bucket, _ = gridfs.NewBucket(MongoUtil)
	} else {
		// 使用传入的文件集合名称
		bucketOptions := options.GridFSBucket().SetName(collName)
		bucket, _ = gridfs.NewBucket(MongoUtil, bucketOptions)
	}
	return bucket
}
